var id;
var urlType = ly.getUrlParam("type");
var roleArr = []; // 角色列表

$(function() {
  id = ly.getUrlParam("id");
  
  if (urlType == 1) {
    // 新增
    getRoles(); // 获取角色列表
    $("#level").getSelect({
      type: "radio",
      asName: "level",
      list: [{ "value": "1", "display": "管理员" }, { "value": "2", "display": "超级管理员" }],
      default: 1
    })
  } else {
    $(".title span").text("编辑");
    $(".form").getForm({
      id: id,
      type: "post",
      ajaxform: "true"
    }, function(data) {
      getRoles(data.roleId); // 获取角色列表
      $("#level").getSelect({
        type: "radio",
        asName: "level",
        list: [{ "value": "1", "display": "管理员" }, { "value": "2", "display": "超级管理员" }],
        default: data.level
      })
    });
  }
  //提交
  $("body").on("click", "#save-btn", function(event) {
    event.preventDefault();
    var success = $('.form').validate('submitValidate');
    if (success) {
      //验证通过提交表单
      submitFom();
    }
  })

});

// 获取角色列表
function getRoles(defaultId) {
  roleArr = [];
  request({
    url: site.apiUrl + '/back/role/selectRoleList',
    type: "post",
    data: {
      num: 1,
      size: 10000
    },
    callback: function(f) {
      if (f.code == 200) {
        var forData = f.data.list
        for (var i = 0; i < forData.length; i++) {
          if (forData[i].id != 1) {
            roleArr.push({
              value: forData[i].id,
              display: forData[i].roleName
            })
          }
        }
        $("#roleId").getSelect({
          asName: "roleId",
          type: "select",
          list: roleArr,
          default: defaultId
        });
      } else {
        ly.toast(f.message);
      }
    }
  })
}

/*
 * 提交表单
 */
function submitFom() {
  var nickName = $("#nickName").val();
  var phone = $("#phone").val();
  var passWord = $("#passWord").val();
  var roleId = $("#roleId").val();
  var level = $("#level").find('input[name=level]:checked').val();

  var obj = {};
  var url = site.apiUrl + "/back/menu/role/modifyAdminDepart";
	obj = {
		'nickName': nickName,
    'phone': phone,
    'passWord': passWord,
    'roleId': roleId,
    'level': level
  };
  // if (passWord.length < 24) {
  //   obj.passWord = md5(passWord);
  // } else {
  //   obj.passWord = passWord;
  // }
  // 修改
  if (urlType == 2) {
    var thisId = $("#currentId").val();
    obj.id = thisId;
  }
  request({
    url: url,
    data: obj,
    type: "post",
    ajaxform: "true",
    callback: function(f) {
      if (f.code == 200) {
        if (urlType == 1) {
          ly.alert('保存成功', function() {
            ly.goto("list.html");
          });
        } else {
          ly.alert('编辑成功', function() {
            ly.goto("list.html");
          });
        }
      } else {
        ly.toast(f.message);
      }
    }
  });
}